package com.orangelife.mobile.individual.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.common.sp.UserSp;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.activities.activity.ActivityDetailActivity;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.buyFresh.activity.BuyFreshDetailActivity;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.individual.adapter.MyOrderDetailAdapter;
import com.orangelife.mobile.pay.interfaze.IOuttradenoCallBack;
import com.orangelife.mobile.pay.interfaze.IPayCallBack;
import com.orangelife.mobile.pay.interfaze.IPayManage;
import com.orangelife.mobile.pay.biz.PayManageImpl;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.redeem.activity.RedeemDetailActivity;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Deprecated
/**我的订单适配器*/
public class MyOrderDetailActivity extends OrangeLifeBaseActivity
        implements OnClickListener {
    private LinearLayout llScore, llAllPaid, llPhone, llSurplusTime, llPostage;
    private TextView llTitle;
    private String orderType;
    private String orderId;
    private ListView detailList;
    private MyOrderDetailAdapter<Map<String, Object>> myOrderListViewAdapter;
    private List<Map<String, Object>> orderList;
    private Map<String, Object> map;
    private Map<String, Object> mapList;
    private Map<String, Object> mapLineList;
    private Dialog dialog;
    private TextView tvOrderNum;
    private TextView tvPaidStatus;
    //	private TextView tvPaidMethod;
    private TextView tvOrderPrice;
    private TextView tvOrderTime;
    private TextView tvTotal;
    private TextView tvVoucherTitle;
    private TextView tvVoucherContent;
    private TextView tvPostagePrice;
    /** 邮费 */
    private TextView tvSurplusTime;
    /** 订单剩余时间 */
    private TextView tvUserName, tvUserPhone, tvAddress, tvCallMethod, tvVoucher;

    private Button btnPaid;

    private static final int DETAIL_LIST = 1;
    private static final int APILAY_KEY = 3;
    public static final int APILAY_PAID = 4;
    private static final int POINT_PAID = 5;
    private static final int PAID_STATE = 6;
    private List<String> list;
    private String outtradeno;
    private String money;

    private String voucherValue = "0";
    /** 用来储存电话号码 */
    private String mPhone;

    private IPayManage iPayManage;
    /** 抵用券linearlayout */
    private LinearLayout llVoucher;
    private View viewSurplusTime, viewVoucher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_individual_my_order_detail);
        initView();
        getDataFromIntent();
        setPageLayout();
        getDataFromServer();
        setListItemClick();
    }

    private void setListItemClick() {
        detailList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                ExitApplication.getInstance().addMainActivity(MyOrderDetailActivity.this);
                /**跳转到商品购买详情页*/
                Intent intent = null;
                Bundle bundle = new Bundle();
                if (orderType.equals(Constant.GOOD_TYPE)) {/**购生鲜*/
                    intent = new Intent(MyOrderDetailActivity.this, BuyFreshDetailActivity.class);
                } else if (orderType.equals(Constant.GROUP_TYPE)) {/**团购*/
                    intent = new Intent(MyOrderDetailActivity.this, ActivityDetailActivity.class);
                } else if (orderType.equals(Constant.CREDIT_TYPE)) {/**积分兑换*/
                    intent = new Intent(MyOrderDetailActivity.this, RedeemDetailActivity.class);
                }
                bundle.putSerializable("detail", (Serializable) orderList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void callPhone() {
        OrangePhoneUtil.callCustomerService2(this);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(android.os.Message msg) {
            String json = (String) msg.obj;
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(msg.obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            switch (msg.what) {
                case DETAIL_LIST:
                    jsonToList(msg);
                    try {
                        setData(jsonObject);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    getPaidStatus();
                    break;
                case APILAY_KEY:
                    /** 支付宝key */
                    try {
                        jsonObject.put("outtradeno", outtradeno);
                        jsonObject.put("totalCost", mapList.get("totalCost").toString());
                        callBack(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case POINT_PAID:
                    /** 积分支付 */
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.point_paid_success));

                    Map<String, Object> mapList = (Map<String, Object>) JSONHelper.jsonToMap(json).get(
                            "entity");
                    UserSp.setPoint(String.valueOf(mapList.get("score")));
                    try {
                        if (mapList.get("tradestatus").toString().equals("2")) {
                            tvPaidStatus.setText(getResources().getString(
                                    R.string.paided));
                        }
                    } catch (NotFoundException e) {
                        e.printStackTrace();
                    }
                    setPaidColor();
                    break;
                case PAID_STATE:
                    json = (String) msg.obj;
                    mapList = (Map<String, Object>) JSONHelper.jsonToMap(json).get(
                            "entity");
                    setPaidStatus(mapList);
                    break;
                case Constant.WHAT_ERROR_HTTP:
//				ToastHelper.getInstance()._toast(
//						getResources().getString(R.string.net_new_request));
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case Constant.WHAT_ACTIVE_UNEXIST:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case Constant.WHAT_TOKEN_EXPIRED:
                    isLogin(dialog);
                    break;
                default:
                    break;
            }
            if (dialog != null)
                DialogHelper.closeDialog(dialog);
        }

        /**
         * 解析数据为List
         *
         * @param msg
         */
        @SuppressWarnings("unchecked")
        private void jsonToList(Message msg) {
            String json = (String) msg.obj;
            mapList = (Map<String, Object>) JSONHelper.jsonToMap(json).get(
                    "entity");
            if (orderType.equals(Constant.GOOD_TYPE)
                    || orderType.equals(Constant.GROUP_TYPE)
                    || orderType.equals(Constant.CREDIT_TYPE)) {
                /** 商品和团购类型 */
                orderList = (List<Map<String, Object>>) mapList
                        .get("goodsInfo");
            } else if (orderType.equals(Constant.LINE_TYPE)) {
                /** 线下活动类型 */
                mapLineList = (Map<String, Object>) mapList.get("goodsInfo");
                orderList.add(mapLineList);
            }
            myOrderListViewAdapter.setList(orderList);
            myOrderListViewAdapter.notifyDataSetChanged();
        }

        /**
         * 设置详情数据
         *
         * @throws JSONException
         */
        private void setData(JSONObject jsonObject) throws JSONException {
            orderList = (List<Map<String, Object>>) mapList
                    .get("goodsInfo");
            if (mapList.get("shipName").equals("null")) {
                tvUserName.setText("");
            } else {
                tvUserName.setText(mapList.get("shipName").toString());
            }
            tvUserPhone.setText(mapList.get("shipPhone").toString());
            if (mapList.get("shipAddr").equals("null")) {
                tvAddress.setText("");
            } else {
                tvAddress.setText(mapList.get("shipAddr").toString());
            }
            tvOrderNum.setText(mapList.get("orderID").toString());
            tvPaidStatus.setText(mapList.get("payStatus").toString());
//			tvPaidMethod.setText(mapList.get("payName").toString());
            if (orderList.get(0).get("couponName") != null) {
//			   tvVoucherTitle.setText(orderList.get(0).get("couponName").toString());
                tvVoucherContent.setText(orderList.get(0).get("couponValue").toString() + "元抵用券");
                voucherValue = orderList.get(0).get("couponValue").toString();
                tvVoucher.setText("抵用券支付" + voucherValue);
            } else {
                tvVoucher.setText("");
                llVoucher.setVisibility(View.GONE);
                viewVoucher.setVisibility(View.GONE);
            }

            tvOrderPrice.setText(Constant.RMB_FLAG + mapList.get("totalCost").toString());
//			String date = DateUtil.getInstance().tranLongForDate2(
//					Long.valueOf(mapList.get("orderTime").toString()));
            tvOrderTime.setText(DateUtil.getInstance().tranStringForDate(mapList.get("orderTime").toString()));
            if (orderType.equals(Constant.CREDIT_TYPE)) {
                tvTotal.setText(mapList.get("totalCost").toString() + "积分");
                tvOrderPrice.setText((int) (Double.parseDouble(mapList.get("totalCost").toString())) + "积分");
                llPostage.setVisibility(View.GONE);
            } else {
                tvTotal.setText(Constant.RMB_FLAG + mapList.get("totalCost").toString());
                /**邮费为0*/
                if (Double.parseDouble(mapList.get("shipCost").toString()) > 0) {
                    tvPostagePrice.setText(Constant.RMB_FLAG + mapList.get("shipCost"));
                } else {
                    tvPostagePrice.setText("免邮");
                }
            }

            /**团购剩余时间显示*/
            if (orderType.equals(Constant.GROUP_TYPE) && (mapList.get("payStatus").toString().equals(getResources().getString(R.string.unpaid)))) {/**未支付*/
                llSurplusTime.setVisibility(View.VISIBLE);
                viewSurplusTime.setVisibility(View.VISIBLE);
                tvSurplusTime.setText(DateUtil.getInstance().setDaysTranHoursAndMinutes(Long.valueOf(mapList.get("time").toString())));
                if (tvSurplusTime.getText().toString().equals("0分钟")) {
                    llSurplusTime.setVisibility(View.GONE);
                    tvPaidStatus.setText("已超时");
                    llAllPaid.setVisibility(View.GONE);
                }
            }
            mPhone = jsonObject.get("hotline").toString();
        }

        ;
    };

    /**
     * 设置支付完成后的支付按钮颜色
     */
    private void setPaidColor() {
        btnPaid.setEnabled(false);
        btnPaid.setBackgroundResource(R.drawable.shape_btn_gray);
    }

    private void setPaidStatus(Map<String, Object> mapList) {
        if (mapList.get("tradestatus").equals("2")) {
            tvPaidStatus.setText(getResources().getString(R.string.paided));
        } else if (mapList.get("tradestatus").equals("3")) {
            tvPaidStatus.setText(getResources().getString(R.string.paiding));
        }
    }

    @SuppressWarnings("deprecation")
    private void getApilayPaidStatus() {
        Map<String, Object> rootMap = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("outTradeNo", outtradeno);
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_PAID_STATUS);
        rootMap.put("wat", PAID_STATE);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    @SuppressWarnings("deprecation")
    private void getKeyFromServer() {
        String url = Constant.URL_APILAY_KEY;
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("url", url);
        rootMap.put("wat", APILAY_KEY);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 判断支付状态，未支付显示支付按钮，已支付不显示
     */
    private void getPaidStatus() {
        if (mapList.get("payStatus").equals(
                getResources().getString(R.string.unpaid))) {
            /** 未支付 */
//			llPaidMethod.setVisibility(View.GONE);
            llAllPaid.setVisibility(View.VISIBLE);
        } else {
//			llPaidMethod.setVisibility(View.VISIBLE);
            llAllPaid.setVisibility(View.GONE);
        }
    }


    private void setPageLayout() {
        orderList = new ArrayList<Map<String, Object>>();
        myOrderListViewAdapter = new MyOrderDetailAdapter<Map<String, Object>>(
                this, orderList, orderType);
        detailList.setAdapter(myOrderListViewAdapter);
        setListViewHeightBasedOnChildren(detailList);
        myOrderListViewAdapter.notifyDataSetChanged();
    }

    @SuppressWarnings("deprecation")
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(
                MyOrderDetailActivity.this, "加载数据中...");
        dialog.show();
        String url = null;
        if (orderType.equals(Constant.GOOD_TYPE)
                || orderType.equals(Constant.GROUP_TYPE)
                || orderType.equals(Constant.CREDIT_TYPE)) {
            /** 商品和团购 */
            url = Constant.URL_ORDER_GROUP_DETAIL + orderId;
        } else if (orderType.equals(Constant.LINE_TYPE)) {
            /** 线下活动 */
            llPhone.setVisibility(View.VISIBLE);
            url = Constant.URL_ORDER_LINE_DETAIL + orderId;
        }
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("url", url);
        rootMap.put("wat", DETAIL_LIST);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    @SuppressWarnings("unchecked")
    private void getDataFromIntent() {
        map = (Map<String, Object>) getIntent().getExtras().getSerializable(
                "map");
        if (map != null && map.size() != 0) {
            orderId = map.get("orderID").toString();
            orderType = map.get("orderType").toString();
        } else {
            orderId = getIntent().getStringExtra("id");
        }

    }

    private TextView tv_help_phone;

    private void initView() {
//		llPaidMethod = (LinearLayout) findViewById(R.id.ll_paid_method);
        viewSurplusTime = (View) findViewById(R.id.viewSurplusTime);
        viewVoucher = (View) findViewById(R.id.viewVoucher);
        llSurplusTime = (LinearLayout) findViewById(R.id.ll_surplus_time);
        llPostage = (LinearLayout) findViewById(R.id.ll_postage);
        llPhone = (LinearLayout) findViewById(R.id.ll_phone);
        tvVoucher = (TextView) findViewById(R.id.tvVoucher);
        tvCallMethod = (TextView) findViewById(R.id.tvCallMethod);
        tvCallMethod.setOnClickListener(this);
        tv_help_phone = (TextView) findViewById(R.id.tv_help_phone);
        tv_help_phone.setOnClickListener(this);
        llAllPaid = (LinearLayout) findViewById(R.id.includePay);
        llScore = (LinearLayout) findViewById(R.id.ll_score);
        llVoucher = (LinearLayout) findViewById(R.id.llVoucher);
        list = new ArrayList<String>();
        detailList = (ListView) findViewById(R.id.lv_order_detail);
        llTitle = (TextView) findViewById(R.id.tv_title);
        tvOrderNum = (TextView) findViewById(R.id.tv_order_id);
        tvPaidStatus = (TextView) findViewById(R.id.tv_paid_status);
//		tvPaidMethod = (TextView) findViewById(R.id.tv_paid_method);
        tvOrderTime = (TextView) findViewById(R.id.tv_order_time);
        tvOrderPrice = (TextView) findViewById(R.id.price);
        tvTotal = (TextView) findViewById(R.id.tv_total);
        tvUserName = (TextView) findViewById(R.id.tv_username);
        tvUserPhone = (TextView) findViewById(R.id.tv_userphone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvVoucherTitle = (TextView) findViewById(R.id.tvVoucherTitle);
        tvVoucherContent = (TextView) findViewById(R.id.tvVoucherContent);
        tvPostagePrice = (TextView) findViewById(R.id.tvPostagePrice);
        tvSurplusTime = (TextView) findViewById(R.id.tvSurplusTime);
        btnPaid = (Button) findViewById(R.id.btn_paid);
        btnPaid.setOnClickListener(this);
        llTitle.setText(getResources().getString(R.string.order_detail));
        llScore.setVisibility(View.INVISIBLE);
//		llVoucher.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_paid:
                if (mapList.get("payName").equals(
                        getResources().getString(R.string.alipay)) ||
                        mapList.get("payName").equals(
                                getResources().getString(R.string.balance_payment))) {
                    iPayManage = new PayManageImpl(new IOuttradenoCallBack() {
                        @Override
                        public void data(JSONObject jsonObject) {
                            ExitApplication.getInstance().addPaidActivity(MyOrderDetailActivity.this);
                            try {
                                outtradeno = jsonObject.get("outtradeno").toString();
                                money = jsonObject.get("money").toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Bundle bundle = new Bundle();
                            bundle.putString("totalPrice", Constant.RMB_FLAG + mapList.get("totalCost").toString());
                            bundle.putString("totalCost", mapList.get("totalCost").toString());
                            bundle.putString("outtradeno", outtradeno);
                            bundle.putString("couponCost", voucherValue);
                            bundle.putString("orderID", orderId);
                            bundle.putString("money", money);
                            bundle.putString("orderInfo", String.valueOf(mapList.get("orderContent")));
                            bundle.putString("orderType", String.valueOf(mapList.get("orderType")));
                            bundle.putBoolean("orderList", true);
                            bundle.putString("status", "goods");
                            bundle.putInt("type", 5);
                            Intent intent = new Intent(MyOrderDetailActivity.this, UsersPaidActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                    iPayManage.getOuttradenoFromServer(mapList.get("orderID").toString(), -1);
                } else {
                    sendCreditRequest();
                }

                break;
            case R.id.tv_help_phone:
                callPhone();
                break;
            case R.id.tvCallMethod:
                callPhone();
                break;
            case R.id.llVoucher:
                ToastHelper.getInstance()._toast("目前暂不支持使用抵用券");
                break;
            default:
                break;
        }
    }

    @SuppressWarnings("deprecation")
    private void sendCreditRequest() {
        /** 判断当前积分是否足够支付订单 */
        if (Integer.parseInt(getTotalCredit()) < Double.parseDouble(mapList.get("totalCost")
                .toString())) {
            Toast.makeText(this, "您的积分不足，暂时不能支付", Toast.LENGTH_SHORT).show();
        } else {
            ExitApplication.getInstance().addMainActivity(MyOrderDetailActivity.this);
            Bundle bundle = new Bundle();
            Intent intent = new Intent(MyOrderDetailActivity.this, UsersPaidActivity.class);
            bundle.putString("totalPrice", tvTotal.getText().toString());
            bundle.putString("totalCost", String.valueOf(mapList.get("totalCost")));
            bundle.putString("orderType", String.valueOf(mapList.get("orderType")));
            bundle.putString("orderInfo", orderList.get(0).get("goodsName").toString() + "X" + orderList.get(0).get("goodsCount"));
            bundle.putString("orderID", orderId);
            bundle.putInt("type", 6);
            bundle.putBoolean("orderList", true);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    /** 处理ScrollView嵌套ListView的冲突问题，目前v1.1.0版本，商品清单只会有一条数据 */
    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        /* 核心，即处理ListView的Item的高度 */
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private void callBack(JSONObject jsonObject) {
        iPayManage = new PayManageImpl(new IPayCallBack() {
            @Override
            public void success() {
                Toast.makeText(MyOrderDetailActivity.this, "支付成功",
                        Toast.LENGTH_SHORT).show();
                getApilayPaidStatus();
                setPaidColor();
            }

            @Override
            public void handling() {
                Toast.makeText(MyOrderDetailActivity.this, "支付结果确认中",
                        Toast.LENGTH_SHORT).show();
                getApilayPaidStatus();
                setPaidColor();
            }

            @Override
            public void fail() {
                Toast.makeText(MyOrderDetailActivity.this, "支付失败",
                        Toast.LENGTH_SHORT).show();
            }
        });
        iPayManage.setParameter(MyOrderDetailActivity.this, jsonObject);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data.getStringExtra("voucher") != null) {
                tvTotal.setText(Constant.RMB_FLAG + (DecimalUtil.add(mapList.get("totalCost").toString(), data.getStringExtra("voucher"))));
            }
        }
    }
}
